package net.dgg.rz.production.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonService;
import net.dgg.rz.common.utils.DataTableResponse;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.ProductNodeDao;
import net.dgg.rz.production.dao.ProductNodeFlowDao;
import net.dgg.rz.production.dao.PunishSchemeDao;
import net.dgg.rz.production.entity.*;
import net.dgg.rz.production.exception.FlowNodeExcption;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.rz.production.service.FlowNodeService;
import net.dgg.rz.production.service.ProductOrderService;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程节点配置controller
 * Created by cuipeng on 2018/12/14.
 */
@Controller
@RequestMapping("/rzsc/flow")
public class FlowNodeController extends DggBaseController{

    @Autowired
    private FlowNodeService flowNodeService;

    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private ProductOrderService productOrderService;//主订单service
    @Autowired
    private PunishSchemeDao punishSchemeDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ProductNodeFlowDao productNodeFlowDao;
    /**
     * 节点管理列表页(old)
     *
     * @return
     */
    @RequestMapping(value = "/index")
    public String index() {
        /*return "rzsc/nodemanager/flow_manager_list";*/
        return "rzsc/nodemanager/flow_manager_list_new";
    }
    /**
     * 节点管理列表页(new)
     *
     * @return
     */
    @RequestMapping(value = "/index_new")
    public String indexNew() {
        return "rzsc/nodemanager/flow_manager_list_new";
    }

    /**
     * @Title: 查询出全部节点流程
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    @RequestMapping(value = "search_all_node_flow")
    @ResponseBody
    public DggRestResponse searchAllNodeFlow(@RequestParam Map params) {
        try {
            Map fileMap = new HashMap();
            fileMap.put("updateTime", "updateTime");
            String[] colNames = new String[]{"bigformatCode", "businessCode"};
            //查询模板时需要转换产品id
            if(params != null && StringUtils.isNotEmpty(params.get("productCode"))){
                Long productCode = commonService.getSerialId(Long.parseLong(params.get("productCode").toString()));
                params.put("productCode",productCode);
            }
            List list = flowNodeService.findAllFlowWithPage(params);
            list = translateUtil.translateList(colNames, list);
            return new DataTableResponse().data(params,list);
        } catch (ProductOrderExcption e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 节点管理——新建流程页(old)
     * @return cuipeng
     * @creat_date: 2018/12/14
     */
    @RequestMapping(value = "/creat_new_flow")
    public String flowCreate() {
        return "rzsc/nodemanager/flowcreate_tabpage";
    }

    /**
     * 节点管理——新建流程页(new)
     * @return cuipeng
     * @creat_date: 2018/12/14
     */
    @RequestMapping(value = "/creat_new_flow_new")
    public String flowCreateNew() {
        return "rzsc/nodemanager/flowcreate_tabpage_new";
    }

    /**
     * @Title:节点管理——新建流程保存
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    //@NLog
    //@AuthOpt(code = "ZZSC_NODEMANAGER_CREATEFLOW")
    @RequestMapping(value = "/create_flow_save")
    @ResponseBody
    @SuppressWarnings("all")
    public DggRestResponse createNewNodeFlowSave(@RequestParam Map params) {
        try {
            flowNodeService.saveFlow(params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }

    }
    /**
     * @Title:节点管理——新建流程保存(新)
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    @RequestMapping(value = "/create_flow_save_new")
    @ResponseBody
    @SuppressWarnings("all")
    public DggRestResponse createNewNodeFlowSaveNew(@RequestParam Map params) {
        try {
            flowNodeService.saveFlowNew(params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }

    }

    /**
     * 节点管理——流程编辑页
     *
     * @return
     */
    @RequestMapping(value = "/flowedit_tabpage")
    public String flowEdit(@RequestParam Map params, Model model) {
        params.put("flag", "1");
        ProductNodeFlow rzFlow = flowNodeService.findFlowById(params);
        model.addAttribute("rzFlow", rzFlow);
        return "rzsc/nodemanager/flowedit_tabpage";
    }

    /**
     * 节点管理——流程编辑页(新)
     *
     * @return
     */
    @RequestMapping(value = "/flowedit_tabpage_new")
    public String flowEditNew(@RequestParam Map params, Model model) {
        ProductNodeFlow rzFlow = flowNodeService.findFlowById(params);
        model.addAttribute("rzFlow", rzFlow);
        return "rzsc/nodemanager/flowedit_tabpage_new";
    }

    /**
     * @Title:保存流程
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    //@NLog
    //@AuthOpt(code = "ZZSC_NODEMANAGER_EDITFLOW")
    @RequestMapping(value = "/edit_flow_save")
    @ResponseBody
    public DggRestResponse editNodeFlowSave(@RequestParam Map params) {
        try {
            flowNodeService.saveFlow(params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 节点管理——打开流程节点编辑页
     *
     * @return
     */
    @RequestMapping(value = "/open_edit_flownode_page")
    public String openEditFlowNodePage(@RequestParam Map params, Model model) {
        params.put("flag", "1");
        ProductNodeFlow rzFlow = flowNodeService.findFlowById(params);

        Map nodeFieldQueryMap = new HashMap();
        nodeFieldQueryMap.put("bigformatCode", rzFlow.getBigformatCode());
        nodeFieldQueryMap.put("flag", "1");
        List<ProductNodeField> sc_NodeFieldList = flowNodeService.findNodefield(nodeFieldQueryMap);

        Map nodeQueryMap = new HashMap();
        nodeQueryMap.put("flowId", params.get("flowId").toString());
        nodeQueryMap.put("flag", "1");
        List<ProductNode> sc_NodeList = flowNodeService.findNodeCenterById(nodeQueryMap);
        ProductNode nodeJd = flowNodeService.findNodeJdById(nodeQueryMap, sc_NodeList);
        /*ProductNode nodeQzWj = flowNodeService.findNodeQzWjById(nodeQueryMap, sc_NodeList);*/
        ProductNode nodeWj = flowNodeService.findNodeWjById(nodeQueryMap, sc_NodeList);
        ProductNode nodeFk = flowNodeService.findNodeFkById(nodeQueryMap, sc_NodeList);
        model.addAttribute("rzFlow", rzFlow);
        model.addAttribute("nodeFieldList", sc_NodeFieldList);
        model.addAttribute("nodeJd", nodeJd);
        model.addAttribute("nodeFk",nodeFk);
        /*model.addAttribute("nodeQzWj", nodeQzWj);*/
        model.addAttribute("nodeWj", nodeWj);
        model.addAttribute("nodeList", sc_NodeList);
        String returnUrl = "rzsc/nodemanager/flownode_edit_tabpage";
        if(StringUtils.isNotEmpty(rzFlow.getIsOld()) && rzFlow.getIsOld().equals(1)){
            //扣罚方案
            PunishScheme p = new PunishScheme();
            p.setBusinessTypeCode(rzFlow.getBigformatCode());
            model.addAttribute("kfList",punishSchemeDao.queryList(p));
            returnUrl = "rzsc/nodemanager/flownode_edit_tabpage_new";
        }
        return returnUrl;
    }

    /**
     * @Title:节点保存
     * @author: cuipeng
     * @creat_date: 2018/5/21
     **/
    //@NLog
    //@AuthOpt(code = "ZZSC_NODEMANAGER_EDITFLOWNODE")
    @RequestMapping(value = "/query_node_field_list")
    @ResponseBody
    public DggRestResponse queryNodeFieldList(ProductNode node, @RequestParam Map params) {
        try {
            Map nodeFieldQueryMap = new HashMap();
            nodeFieldQueryMap.put("flag", "1");
            List<ProductNodeField> sc_NodeFieldList = flowNodeService.findNodefield(nodeFieldQueryMap);
            return this.getSuccessResponse(sc_NodeFieldList);
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * @Title:节点保存
     * @author: cuipeng
     * @creat_date: 2018/5/21
     **/
    //@NLog
    //@AuthOpt(code = "ZZSC_NODEMANAGER_EDITFLOWNODE")
    @RequestMapping(value = "/nodesave")
    @ResponseBody
    public DggRestResponse NodeSave(ProductNode node, @RequestParam Map params) {
        try {
            flowNodeService.saveNode(node, params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 节点管理——复制流程页
     *
     * @return
     */
    @RequestMapping(value = "/flowcopy_tabpage")
    public String flowCopy(@RequestParam Map params, Model model) {
        params.put("flag", "1");
        ProductNodeFlow rzFlow = flowNodeService.findFlowById(params);
        model.addAttribute("rzFlow", rzFlow);
        return "rzsc/nodemanager/flowcopy_tabpage";
    }

    /**
     * 节点管理——复制流程页(新)
     *
     * @return
     */
    @RequestMapping(value = "/flowcopy_tabpage_new")
    public String flowCopynew(@RequestParam Map params, Model model) {
        params.put("flag", "1");
        ProductNodeFlow rzFlow = flowNodeService.findFlowById(params);
        model.addAttribute("rzFlow", rzFlow);
        return "rzsc/nodemanager/flowcopy_tabpage_new";
    }

    /**
     * @Title:复制流程节点保存
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    //@AuthOpt(code = "ZZSC_NODEMANAGER_COPYFLOW")
    @RequestMapping(value = "/copy_flow_save")
    @ResponseBody
    public DggRestResponse copyNodeFlowSave(@RequestParam Map params) {
        try {
            flowNodeService.copyFlowAndFlow(params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * @Title:复制流程节点保存(新)
     * @author: cuipeng
     * @creat_date: 2018/12/14
     **/
    //@AuthOpt(code = "ZZSC_NODEMANAGER_COPYFLOW")
    @RequestMapping(value = "/copy_flow_save_new")
    @ResponseBody
    public DggRestResponse copyNodeFlowSaveNew(@RequestParam Map params) {
        try {
            flowNodeService.copyFlowAndFlowNew(params);
            return this.getSuccessResponse("保存成功");
        }catch (CommonExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }


    /**
     *弹出更新节点页面
     * @param id  主订单id
     * @author: chenzaidong
     * @return
     */
    @RequestMapping(value = "/openUpdateNode.html")
    //@NLog()
    public ModelAndView openUpdateNode(Long id,@RequestParam(required = false) String nodeId) {

        try{
            //验证当前用户是否可以操作该主订单
            productOrderService.validationUpdateNode(id,"openUpdateNode",null);
            ModelAndView map = new ModelAndView();

            //主订单
            ProductOrder productOrder = productOrderService.selectByPrimaryKey(id);
            ValidateUtils.isTrue(productOrder.getStatus().equals(ScProductConstant.RZSCORDER_STATUS02), ProductOrderExcption.class
                    , "此订单当前状态不是办理中不能操作该订单，请刷新列表！");

            //查节点
            Map mapNode = new HashMap();
            List<ProductNode> nodelist = new ArrayList<ProductNode>();
            if(StringUtils.isNotEmpty(productOrder.getNodeJson())){
                nodelist = JSONArray.parseArray(productOrder.getNodeJson(), ProductNode.class);
            }else{
                mapNode.put("flowId", String.valueOf(productOrder.getNodeFlowId()));
                mapNode.put("version",productOrder.getVersion());
                ProductNodeFlow productNodeFlow= productNodeFlowDao.selectFlowById(mapNode);
                Integer old = productNodeFlow.getIsOld();
                if (old==null||old.equals(0)) {
                    nodelist = flowNodeService.queryByFlowId(mapNode);
                }else {
                    nodelist= flowNodeService.queryByFlowIdAndVersion(mapNode);
                }
            }
            if(nodelist == null || nodelist.size()<1){
                throw new FlowNodeExcption("主订单的流程下未查询到节点");
            }
            int sort = 1;
            Integer nodelistSize = nodelist.size();
            if (productOrder.getLatestEndNodeId() != null && nodeId == null) {
                for (ProductNode scProductNode : nodelist) {
                    if(scProductNode.getId().equals(productOrder.getLatestEndNodeId())){
                        sort = scProductNode.getSort()+1;
                        break;
                    }
                }
                if(sort<=nodelistSize){
                    for (ProductNode scProductNode : nodelist) {
                        if(sort==scProductNode.getSort().intValue()){
                            nodeId = scProductNode.getId().toString();
                            break;
                        }
                    }
                }
            }
            //去除接单
            nodelist.remove(0);
            map.addObject("nodelist", nodelist);//添加的流程节点
            map.addObject("productOrder", productOrder);//主订单
            map.addObject("code", productOrder.getBusinessTypeCode());//业态标识code
            map.addObject("fileType", "refund");//上传附件后缀
            map.addObject("nodeId", nodeId);//所选节点ID
            map.setViewName("rzsc/nodemanager/open_update_node");
            return map;
        }catch (FlowNodeExcption e){
            e.printStackTrace();
            throw new FlowNodeExcption(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            throw new FlowNodeExcption(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            throw new FlowNodeExcption(ScProductConstant.SYS_ERROR);
        }

    }


    /**
     * 保存节点更新
     * @param params
     * @author: chenzaidong
     * @return
     */
    @RequestMapping("/saveNodeUpdate")
    @ResponseBody
    public Object saveNodeUpdate(@RequestParam Map params) {
        try {
           flowNodeService.saveNodeUpdate(params);
            return this.getSuccessResponse(null);
        } catch (FlowNodeExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (ProductOrderExcption e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 计算两个时间之间的工作日有多少天
     */
    @RequestMapping("/getWorkDays")
    @ResponseBody
    public DggRestResponse getWorkDays(@RequestParam Map map) {
        try {
            return this.getSuccessResponse(flowNodeService.getWorkDays(map));
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 流程节点数据补充（导入以前老数据 没有接单，放款，强制完结，完结这四个固定节点的时候 自动补充进去）
     *
     */
    @RequestMapping("/supplement_flow_node")
    @ResponseBody
    public DggRestResponse supplementFlowNode() {
        try {
            flowNodeService.supplementFlowNode();
            return this.getSuccessResponse("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }


    /**
     * 根据渠道+商品查询节点信息列表
     */
    @RequestMapping("/nodes_by_goodsId_channelId")
    @ResponseBody
    public DggRestResponse nodesByGoodsIdChannelId(Long channelId,Long goodsId){
        try {
            return this.getSuccessResponse(flowNodeService.nodesByGoodsIdChannelId(channelId,goodsId));
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 查询所有节点信息列表（根据节点名字分组）
     */
    @RequestMapping("/query_all_nodes")
    @ResponseBody
    public DggRestResponse queryAllNodes(){
        try {
            return this.getSuccessResponse(productNodeDao.queryAllNodes());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }


    /**
     * 根据产品ID查询商品信息列表(已弃用)
     */
    /**
     * 查询所有节点信息列表（根据节点名字分组）
     */
    @RequestMapping("/query_goods_by_productId")
    @ResponseBody
    public DggRestResponse queryGoodsByProductId(Long productId){
        try {
            ValidateUtils.strNotEmpty(productId,ProductOrderExcption.class,"产品id不能为空");
            Map map = new HashMap();
            map.put("proId", productId);
            Map goods = cmsService.productInfo(map);
            return this.getSuccessResponse(goods.get("goodsList"));
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }



}
